<?php

/**
 * @category Noginn
 * @package Noginn_Geocoder
 */
class Noginn_Geocoder
{
    /**
     * The geocoder adapter
     *
     * @var Noginn_Geocoder_Adapter_Abstract
     */
    protected $_adapter = null;
    
    protected static $_cache = null;
    
    /**
     * Constructor.
     *
     * @param Noginn_Geocoder_Adapter_Abstract $adapter
     * @return void
     */
    public function __construct(Noginn_Geocoder_Adapter_Abstract $adapter)
    {
        $this->_adapter = $adapter;
    }
    
    /**
     * Returns the geocoder adapter
     *
     * @return Noginn_Geocoder_Adapter_Abstract
     */
    public function getAdapter()
    {
        return $this->_adapter;
    }
    
    /**
     * Sets a cache for all instances of Zend_Geocode
     *
     * @param  Zend_Cache_Core $cache Cache to store to
     * @return void
     */
    public static function setCache(Zend_Cache_Core $cache)
    {
        self::$_cache = $cache;
    }

    /**
     * Returns the set cache
     *
     * @return Zend_Cache_Core The set cache
     */
    public static function getCache()
    {
        return self::$_cache;
    }
    
    /**
     * Factory for Noginn_Geocoder_Adapter_Abstract classes.
     *
     * @param string $adapter The name of the adapter class 
     * @return Noginn_Geocoder_Adapter_Abstract
     */
    public static function factory($adapter, $config = array())
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        }
        
        // Verify that adapter parameters are in an array.
        if (!is_array($config)) {
            throw new Zend_Db_Exception('Adapter parameters must be in an array or a Zend_Config object');
        }
        
        switch ($adapter) {
            case 'GeocoderUs':
                $geocoder = new self(new Noginn_Geocoder_Adapter_GeocoderUs($config));
                break;
            case 'GoogleAjaxSearch':
                $geocoder = new self(new Noginn_Geocoder_Adapter_GoogleAjaxSearch($config));
                break;
            case 'GoogleMaps':
                $geocoder = new self(new Noginn_Geocoder_Adapter_GoogleMaps($config));
                break;
            case 'Multimap':
                $geocoder = new self(new Noginn_Geocoder_Adapter_Multimap($config));
                break;
            case 'Yahoo':
                $geocoder = new self(new Noginn_Geocoder_Adapter_Yahoo($config));
                break;
            default:
                throw new Zend_Exception("Adapter class for '$adapter' could not be found");
        }
        
        return $geocoder;
    }
    
    /**
     * Geocode the address
     *
     * @param string|array $address 
     * @return Noginn_Geocoder_LocationList
     */
    public function geocode($address)
    {
        return $this->_adapter->geocode($address);
    }
}